import copy
import urllib.parse
from typing import Awaitable

from wintersweet.asyncs.http.api import request
from wintersweet.asyncs.interface.http import HttpInterface


class ServiceClient:
    """
    便捷的客户端管理器
    >>> import aiohttp.hdrs
    >>> interface = HttpInterface(aiohttp.hdrs.METH_GET, '/v1/xxx/sss')
    >>> service  = ServiceClient('https://www.xxxx.com')
    >>> resp = await service.request(interface, params={'aa': 12, 'bb': 23})
    """
    def __init__(self, url_base, headers=None):
        self._url_base = url_base
        self._headers = headers or {}

    @property
    def url_base(self):

        return self._url_base

    @property
    def headers(self):

        return self._headers

    def request(self, interface: HttpInterface, **kwargs) -> Awaitable:
        _kwargs = copy.deepcopy(kwargs)

        if 'headers' in _kwargs and isinstance(_kwargs['headers'], dict):
            _kwargs['headers'].update(self._headers)
        else:
            _kwargs['headers'] = self._headers

        url = urllib.parse.urljoin(self.url_base, interface.uri)
        return request(method=interface.method, url=url, **_kwargs)
